
import Http from '@/services/api/index';
const Config = require('./../config/base_config.js')
const Storage = require('@/utils/storage.js')
const Util = require('./../utils/util.js')

/**
 * 登录功能
 */
const login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: async (res) => {
        if (res.code) {
          try {
            // 调用登录接口
            await Http.post('/api/auth/login', {
              code: res.code
            }, {
              skipAuth: true 
            }).then(res => {
              console.log("调用登录接口返回数据", res);
              if (res.data.code === 200) {
                // 存储token和用户信息
                let access_expires_in = Util.timeToSeconds(res.data.access_expires_in);
                let refresh_expires_in = Util.timeToSeconds(res.data.refresh_expires_in);
                console.log(access_expires_in, refresh_expires_in);
                Storage.set('access_token', res.data.access_token, access_expires_in || 5 * 60);
                Storage.set('refresh_token', res.data.refresh_token, refresh_expires_in || 1 * 60 * 60);
                Storage.set('userInfo', res.data.userInfo, refresh_expires_in || 1 * 60 * 60);
                resolve(res.data);
              } else {
                reject(new Error(res.data.message));
              }
            }).catch(err => {
              console.error(err);
              reject(err);
            });
          } catch (error) {
            reject(error);
          }
        } else {
          reject(new Error('登录失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

/**
 * 检查登录状态
 */
const checkLogin = async () => {
  const token = Storage.get('access_token');
  if (!token) {
    return false;
  }
  
  // 可以添加更复杂的检查逻辑，如验证token有效性等
  return true;
};

/**
 * 退出登录
 */
const logout = () => {
  // 清空所有存储的token和用户信息
  Storage.remove('access_token');
  Storage.remove('refresh_token');
  Storage.remove('userInfo');
  
  // 可以添加调用后端注销接口的逻辑
  return Promise.resolve();
};

module.exports = {
  login,
  checkLogin,
  logout
};